//用户数据模块

import { defineStore } from 'pinia';

//请求函数
import { reqLogin } from "@/api/login/index.ts";
import { reqUserInfo } from '@/api/user';
//引入相关的数据类型
import { loginParams } from "@/api/login/type.ts";

//引入路由相关配置
//@ts-ignore,引入路由文件中的常量、权限路由、任意路由配置
import { anyRouter, constantRouter, manageRouter, permissionRouter } from "@/router/index.ts";

//引入router实例,用于动态添加路由表
import router from "@/router/index.ts";


let useUserStore = defineStore("user",{
    state:() => {
        return {
            username:localStorage.getItem("_username") || "",  //用户名
            userToken:localStorage.getItem("token") || "",
            userInfo:{  //用户信息
                id:null,
                username:"",
                nickname:"",
                avatar:""
            },
            dynamicMenuList:[...constantRouter,...manageRouter],  //左侧菜单信息
        }
    },
    actions:{
        //用户登录
        async userLogin(loginParams:loginParams){
            let res = await reqLogin(loginParams);
            console.log("管理员用户登录api",res);
            if(res.code !== 200) {
                //出现错误，抛出异常
                throw new Error(res.msg);
            }
            //登录成功,保存相关数据
            this.username = loginParams.username;
            this.userToken = res.data;
            //将token存储再localStorage
            localStorage.setItem("token",res.data);
            localStorage.setItem("_username",loginParams.username);
        },
        //获取用户信息
        async getUserInfo(){
            if(this.username === '') return;
            let res = await reqUserInfo(this.username);
            //保存获取到的用户信息
            if(res.code === 200){
                this.userInfo.id = res.data.id;
                this.userInfo.username = res.data.username;
                this.userInfo.nickname = res.data.nickname;
                this.userInfo.avatar = res.data.avatar;
                //是否为超级管理员(用户名:admin)用户，是则为其添加权限菜单、权限路由，否则不添加
                if(res.data.username === "admin"){
                    //侧边栏菜单添加上对应的权限路由的菜单信息
                    this.dynamicMenuList = [...constantRouter,...manageRouter,...permissionRouter];
                    //添加对应的权限路由
                    permissionRouter.forEach(item => {
                        router.addRoute(item);
                    })
                }
                //本地存储一份username
                localStorage.setItem("_username",res.data.username);
            }
            console.log("管理员用户信息api",res);
        },
        //用户退出登录
        async userLogout(){
            //发请求退出登录
            //清空用户仓库数据
            this.username = "";
            this.userToken = "";
            this.userInfo = {
                id:null,
                username:"",
                nickname:"",
                avatar:""
            }
            this.dynamicMenuList = [...constantRouter,...manageRouter];
            //清空本地存储数据
            localStorage.clear();
        }
    },
    getters:{

    }
})


export default useUserStore;